import random
import math
import requests
from datetime import datetime, timedelta
import json
import time

# 模拟的起始位置（北京天安门）
start_lat = 39.9087
start_lng = 116.3975

# 模拟移动的速度（度/秒）
speed = 0.0001

# 服务器地址
SERVER_URL = 'http://localhost:9999/api/locations'

def generate_location(current_lat, current_lng, direction):
    """生成单个位置数据"""
    # 随机改变方向
    if random.random() < 0.1:  # 10% 的概率改变方向
        direction = random.uniform(0, 2 * math.pi)
    
    # 计算新的位置
    new_lat = current_lat + speed * math.sin(direction)
    new_lng = current_lng + speed * math.cos(direction)
    
    # 生成位置数据（格式：纬度,经度）
    location = f"{new_lat:.6f},{new_lng:.6f}"
        
    return location, new_lat, new_lng, direction

def send_location(location):
    """发送位置数据到服务器"""
    try:
        # 直接发送字符串数据
        response = requests.post(SERVER_URL, data=location)
        if response.status_code == 200:
            print(f'发送成功: {location}')
        else:
            print(f'发送失败: {response.status_code}')
    except Exception as e:
        print(f'发送错误: {e}')

def main():
    current_lat = start_lat
    current_lng = start_lng
    direction = random.uniform(0, 2 * math.pi)
    
    print('开始发送位置数据...')
    print('按 Ctrl+C 停止')
    
    try:
        while True:
            # 生成新位置
            location, current_lat, current_lng, direction = generate_location(
                current_lat, current_lng, direction
            )
            
            # 发送到服务器
            send_location(location)
            
            # 等待一秒
            time.sleep(1)
            
    except KeyboardInterrupt:
        print('\n停止发送')
    except Exception as e:
        print(f'发生错误: {e}')

if __name__ == '__main__':
    main() 